from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ

# Create your views here.
from oauth.utils import generic_access_token

"""
用户点击 qq登录按钮的时候,前端应该发送一个 ajax请求,来获取要跳转的url

 这个url 是根据 腾讯的文档来生成的

 GET   /oauth/qq/statues/

"""
from django.conf import settings
class OauthQQURLView(APIView):

    def get(self,request):

        state = '/'
        # 1.创建 oauth对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=state)
        # 2.调用方法,获取url
        url = oauth.get_qq_url()
        # url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&redirect_uri=http%3A%2F%2Fwww.meiduo.site%3A8080%2Foauth_callback.html&state=%2F&client_id=101474184"

        return Response({'login_url':url})

"""
前段应该 在用户扫描完成之后,跳转到 http://www.meiduo.site:8080/oauth_callback.html?code=6E2E3F64C34ECFE29222EBC390D29196&state=test
把code 传递给后端,

GET     /oauth/qq/users/?code=xxx

# 1.我们获取到这个code, 通过接口来换去 token
# 2.有了token,就可以换取 oepnid


"""
from rest_framework import status
from .models import OAuthQQUser
from .serializers import OauthQQUserSerializer
class OauthQQUserView(APIView):


    def get(self,request):
        #1.接收code
        code = request.query_params.get('code')
        if code is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        #2.通过code 抽取token
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,)

        access_token = oauth.get_access_token(code)
        openid = oauth.get_open_id(access_token)

        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 说明没有绑定过
            """
            1. 需要对敏感数据进行处理
            2. 数据还需要一个有效期
            """
            # # 我们需要对 openid进行加密处理
            access_token = generic_access_token(openid)
            return Response({'access_token':access_token})
        else:
            #没有异常走else
            #如果有 则说明用户绑定过
            #应该跳转到首页
            #登陆成功了  应该返回token
            from rest_framework_jwt.settings import api_settings

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_DECODE_HANDLER

            payload = jwt_payload_handler(qquser.user)
            token = jwt_encode_handler(payload)

            return Response({
                'token':token,
                'username':qquser.user.username,
                'user_id':qquser.user.id
            })
        # 如果数据库中 有oepnid 则表明用户已经绑定过了
        # 如果数据库中 没有openid 则表明用户没有绑定过了,应该显示绑定界面

    """
    用户点击绑定按钮的时候,前端应该将 手机号,密码,短信验证码,openid(处理过得) 发送给后端

        1. 接收数据
        2. 对数据进行校验 (手机号,密码,短信验证码,openid(处理过得))
            2.1 短信验证码
            2.2 openid(处理过的)
            2.3根据手机号查询用户信息,判断是否存在
        3. 保存数据
        4. 返回响应

        POST

    """


    def post(self, request):
        #1 接收数据
        data = request.data
        #2 对数据进行校验
        serializer = OauthQQUserSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        #3 保存数据
        qquser = serializer.save()
        #4 返回响应
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(qquser.user)
        token = jwt_encode_handler(payload)

        return Response({
            'token': token,
            'username': qquser.user.username,
            'user_id': qquser.user.id
        })









from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadSignature,SignatureExpired
from django.conf import settings
# 1.创建 序列化器
#secret_key             秘钥,一般使用工程的 SECRET_KEY
# expires_in=None       有效期 单位秒
serializer = Serializer(settings.SECRET_KEY,3600)

#2. 组织 加密数据
data = {'openid':'1234567890'}

#3.进行加密处理
token = serializer.dumps(data)
"""
b'eyJpYXQiOjE1NDE4MjE2MTIsImFsZyI6IkhTMjU2IiwiZXhwIjoxNTQxODI1MjEyfQ.
eyJvcGVuaWQiOiIxMjM0NTY3ODkwIn0.
oJhSok5Km327hBA8yoLd64Y3RgqtHHqu9GQ1I5VDDeE'

"""

#4.对数据进行解密
serializer.loads(token)

#5.有效期
serializer = Serializer(settings.SECRET_KEY,1)


data = {'openid':'1234567890'}

token = serializer.dumps(data)


serializer.loads(token)

